<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>测试WebSocet</h1>
    <div>
        <button onclick="stopReceive()">发送停止信号</button>
        <button onclick="startReceive()">发送接收信号</button>
        <button onclick="closeConnect()">断开通信</button>
        <button onclick="openConnect()">重新连接</button>
    </div>

    <div id="box">

    </div>
    <script>
        // 1. 获取websocket的实例
        let ws;
        if(typeof window.WebSocket === "undefined"){
             console.log("浏览器不支持WebSocket协议")
        }else{
             ws = new WebSocket("ws://localhost:3000/wbs/echo"); // try...catch无法捕获
        }

        ws.onopen = function (e) {
           console.log("客户端已成功连接服务器");
        }

        ws.onerror = function (e) {
            console.log(`客户端连接失败`);
        }

        let box = document.getElementById("box");

        ws.onmessage = function (messageEvent) {
            let {origin,data} = messageEvent; // origin：服务器的域  data:服务器推送的数据
            box.innerHTML = data;
        }

        function stopReceive() {
            ws.send("end")
        }

        function startReceive() {
            ws.send("start")
        }

        function closeConnect() {
            ws.close();
            ws = null;
            box.innerHTML = "";
        }

        function openConnect() {
            if(ws){
                alert("请先断开原有连接再尝试新的连接")
            }else{
                ws =  new WebSocket("ws://localhost:3000/wbs/echo");
                ws.onmessage = function (messageEvent) {
                    let {origin,data} = messageEvent; // origin：服务器的域  data:服务器推送的数据
                    box.innerHTML = origin + "-" + data;
                }
            }

        }

    </script>
</body>
</html>